package se.lth.student.axisandroidcam.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import se.lth.student.axisandroidcam.client.Toolbox;

public class ServerIn extends Thread {
	private ServerOut serverOutThread;
	private ServerSocket serverSocket;
	private Socket clientSocket;
	private PrintWriter out;

	public ServerIn(ServerOut networkOutThread) {
		this.serverOutThread = networkOutThread;
	}

	public void run() {
		while (true) {
			// accept, get output & input
			try {
				clientSocket = serverSocket.accept();
				Toolbox.printDebug("Connection established");
				out = new PrintWriter(clientSocket.getOutputStream(), true);
				BufferedReader in = new BufferedReader(new InputStreamReader(
						clientSocket.getInputStream()));
				String fromClient;
				out.println("START");

				while ((fromClient = in.readLine()) != null) {
					int command = 0;
					if (fromClient.equals("MOVIE")) {
						command = 1;
					}
					out.println("MODECHANGE");
					changeMode(command);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void changeMode(int command) {
		if (command == 1) {
			serverOutThread.forceMovie(true);
		} else {
			serverOutThread.forceMovie(false);
		}
	}

	public boolean connect() {
		try {
			serverSocket = new ServerSocket(Server.PORT
					+ (Server.CAMERA_ID * 10) + 1);
			return true;
		} catch (IOException e) {
			Toolbox.printDebug("Socket failed to listen to port: "
					+ (Server.PORT + Server.CAMERA_ID));
			e.printStackTrace();
			return false;
		}
	}

}
